package com.znf.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.znf.biz.system.constant.RedisKeyConstant;
import com.znf.util.JwtUtils;
import com.znf.common.util.RedisUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@Data
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtils jwtUtils;

    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(jwtUtils.getJwtProperties().getHeader());
        if (StrUtil.isBlank(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        Claims claims = jwtUtils.getClaimsByToken(token);
        if (claims == null) {
            throw new JwtException("token异常");
        }
        if (jwtUtils.isExpire(claims)) {
            throw new JwtException("token已过期");
        }
        String username = claims.getSubject();
        String key = RedisKeyConstant.getKey(RedisKeyConstant.AUTH_USER, username);
        Object value = redisUtils.get(key);
        if (value != null) {
            CustomUserDetails userDetails = BeanUtil.fillBeanWithMap((Map) value, new CustomUserDetails(), CopyOptions.create().ignoreNullValue());
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, new ArrayList<>());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
